package net.wicp.tams.plugin.task;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.apiext.TarUtil;
import net.wicp.tams.common.constant.BasePath;

@Mojo(name = "plugin", requiresProject = true, threadSafe = true)
public class PlugIn extends AbstractMojo {

	@Parameter(defaultValue = "lib", required = false, property = "prefix")
	private String libPrefix;

	@Parameter(defaultValue = "${project}")
	private MavenProject project;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		BasePath.projectBasePath = project.getBasedir().getPath();

		File targetDir = new File(BasePath.target.getPath(), project.getArtifactId());
		try {
			if (targetDir.exists()) {
				FileUtils.forceDelete(targetDir);
			}
			FileUtils.forceMkdir(targetDir);
		} catch (Exception e) {
			throw new MojoFailureException(project.getArtifactId() + "目录准备失败", e);
		}

		getLog().info("------------------------复制---------------------");
		try {
			String finalName = project.getBuild().getFinalName();
			String jarFilename = StringUtil.isNull(finalName)
					? String.format("%s-%s.jar", project.getArtifactId(), project.getVersion())
					: String.format("%s.jar", finalName);
			FileUtils.copyFileToDirectory(new File(BasePath.target.getPath(), jarFilename), targetDir);
			FileUtils.copyDirectoryToDirectory(new File(BasePath.target.getPath(), libPrefix), targetDir);
		} catch (IOException e) {
			throw new MojoFailureException("复制打包源文件失败", e);
		}
		getLog().info("------------------------打tar包---------------------");
		TarUtil.compress(targetDir,
				IOUtil.mergeFolderAndFilePath(BasePath.target.getPath(), project.getArtifactId() + ".tar"));
		getLog().info("------------------------dkconf完成---------------------");

	}
}
